package Utils.Concurrent;

import gamePlay.ChainOfLevel;
import gamePlay.LevelMod;
import gamePlay.LongMod;
import gui.LoaderGif;

import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import main.Session;
import main.SharedPref;

import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import Utils.UI.UIUpdater;
import Utils.connections.ConnectionPool;
import datatype.Statistics;
import datatype.User;
import datatype.DBtypes.FilmfromDB;
import datatype.DBtypes.ProgramfromDB;
import datatype.searchtype.SearchResult;
import datatype.searchtype.SearchResult.MediaRes;
import datatype.searchtype.SearchResult.PersonRes;

// class with all the static classes that extends the AsyncTask
// for every task in the gui that uses thread, there is a task here that uses that

public class ThreadTasks {

	public static class Timer extends AsyncTask<Object> {

		public Timer(Display display, Object... vals) {
			super(display, vals);

		}

		@Override
		public Object doInBackground() {

			try {

				// System.out.println("executing new timer " + ++counter);

				for (int counter = SharedPref.timerTime; counter > -1; counter--) {
					UIUpdater.setWidgetText((Widget) vals[0], "" + counter);

					Thread.sleep(1000);

				}

				UIUpdater.timerTimeup(display);

			} catch (InterruptedException e) {
				// e.printStackTrace();
				// System.out.println("kill timer: "+e);
				// System.out.println("timer interrupted, current living timers: "
				// + --counter);
				return null;
			}

			// System.out.println("timer finished normally,current living timers: "
			// + --counter);

			return null;
		}

		@Override
		public void onInterrupt() {
			// TODO Auto-generated method stub

		}
	}

	public static class LoginTask extends AsyncTask<Object> {

		public LoginTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public User doInBackground() throws TaskRunError {
			LoaderGif lg = (LoaderGif) vals[2];
			try {
				// introLoginBTN();

				Statement stm = Session.connectionPool.getStatement(this);
				Session.user = Session.DB.getUserManagment().getUserFromDB(
						(String) vals[0], (String) vals[1], stm);

			} catch (InterruptedException e) {
				// System.out.println("LoginTask interrupted: \n" + e);
				Session.poolForLogin.killAll(lg.getLoaderTask());
				return null;
			}
			Session.poolForLogin.killAll(lg.getLoaderTask());
			lg.hideLoader();
			UIUpdater.loginChangeGUI(display);
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {

			Session.connectionPool.stopDBoperation(this);
		}

	}

	public static class ChangePassTask extends AsyncTask<Object> {

		public ChangePassTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public User doInBackground() throws TaskRunError {
			LoaderGif lg = (LoaderGif) vals[2];
			try {
				int userID = (Integer) vals[0];
				String password = (String) vals[1];

				Statement stm = Session.connectionPool.getStatement(this);
				Session.DB.getUserManagment().changePass(userID, password, stm);
			} catch (InterruptedException e) {
				Session.poolForLogin.killAll(lg.getLoaderTask());
				return null;
			}

			Session.poolForLogin.killAll(lg.getLoaderTask());

			UIUpdater.changePsssGUI();
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class AvailabilityTask extends AsyncTask<Object> {

		public AvailabilityTask(Display display, Object... vals) {
			super(display, vals);

		}

		@Override
		public Boolean doInBackground() throws TaskRunError {
			LoaderRunner loaderR = (LoaderRunner) vals[1];
			Label lbl = (Label) vals[2];
			boolean aval = false;
			try {
				Statement stm = Session.connectionPool.getStatement(this);
				aval = Session.DB.getUserManagment().isUsernameExist(
						(String) vals[0], stm);
			} catch (InterruptedException e) {
				// System.out.println("LoginTask interrupted: \n" + e);
				Session.poolForLogin.killAll(loaderR);
				System.out.println("aval");
				return false;
			}
			Session.poolForLogin.killAll(loaderR);

			String str = (!aval) ? "user name is available!"
					: "user name exists!";
			UIUpdater.setWidgetText(lbl, str);
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class RegistraionTask extends AsyncTask<Object> {

		public RegistraionTask(Display display, Object... vals) {
			super(display, vals);

		}

		@Override
		public Boolean doInBackground() throws TaskRunError {

			String fname = (String) vals[0];
			String lname = (String) vals[1];
			String username = (String) vals[2];
			String password = (String) vals[3];
			LoaderGif lg = (LoaderGif) vals[4];
			Label lbl = (Label) vals[5];
			int id = 0;
			try {

				Statement stm = Session.connectionPool.getStatement(this);
				id = Session.DB.getUserManagment().createUserInDB(fname, lname,
						password, username, stm);

			} catch (InterruptedException e) {
				// System.out.println("LoginTask interrupted: \n" + e);
				Session.poolForLogin.killAll(lg.getLoaderTask());
				return false;
			}
			Session.poolForLogin.killAll(lg.getLoaderTask());
			lg.hideLoader();
			UIUpdater.registrationChangeGUI(display, id);
			Session.connectionPool.stopDBoperation(this);
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);
		}

	}

	public static class NextChainTask extends AsyncTask<Object> {

		public NextChainTask(Display display, Object... vals) {
			super(display, vals);

		}

		@Override
		public Object doInBackground() {

			Button continueBTN = (Button) vals[0];
			LoaderGif lg = (LoaderGif) vals[1];
			try {
				Statement stm = Session.connectionPool.getStatement(this);
				LevelMod game = (LevelMod) Session.game;
				if (game.getChain() == null) {
					game.setChain(Session.quest.getNextLevel(1, stm));
					game.setCurrentLevel((ChainOfLevel) game.getChain());
				} else {
					game.setNextLevel(Session.quest.getNextLevel(game
							.getCurrentLevel().getLevel() + 1, stm));
					// System.out.println("---------------------------"+game.getCurrentLevel().getLevel()+"------------------------------------------------");
				}

			} catch (InterruptedException e) {
				e.printStackTrace();

				Session.poolTheQuestions.killAll(lg.getLoaderTask());
				return null;
			}
			// System.out.println("task");

			Session.poolTheQuestions.killAll(lg.getLoaderTask());
			UIUpdater.setWidgetVisibile(continueBTN, true);
			// UIUpdater.setWidgetText(loadingLBL, "finished loading");

			return null;
		}

		@Override
		public void onInterrupt() {
			// TODO Auto-generated method stub

		}

	}

	public static class NextChainLongTask extends AsyncTask<Object> {
		public NextChainLongTask(Display display, Object... vals) {
			super(display, vals);

		}

		@Override
		public Object doInBackground() {
			Button continueBTN = (Button) vals[0];
			LoaderGif lg = (LoaderGif) vals[1];

			try {

				Statement stm = Session.connectionPool.getStatement(this);
				((LongMod) Session.game).setNextQuestions(Session.quest
						.getNextQuestions(stm));

			} catch (InterruptedException e) {
				// e.printStackTrace();
				Session.poolTheQuestions.killAll(lg.getLoaderTask());
				return null;
			}
			Session.poolTheQuestions.killAll(lg.getLoaderTask());
			UIUpdater.setWidgetVisibile(continueBTN, true);
			// UIUpdater.setWidgetText(loadingLBL, "finished loading");
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);
		}

	}

	public static class UpdateMediaTask extends AsyncTask<Object> {

		public UpdateMediaTask(Display display, Object... vals) {
			super(display, vals);
		}

		@SuppressWarnings("unused")
		@Override
		public Object doInBackground() throws TaskRunError {
			LoaderGif lg = (LoaderGif) vals[1];
			boolean isProgram = (Boolean) vals[2];
			Button cancel = (Button) vals[3];

			try {

				Statement stm = Session.connectionPool.getStatement(this);

				if (isProgram) {
					ProgramfromDB programToupdate = (ProgramfromDB) vals[0];
					Session.DB.getMediaManagment().updateProgram(
							programToupdate, stm);
				} else {
					FilmfromDB filmToUpdate = (FilmfromDB) vals[0];
					Session.DB.getMediaManagment()
							.updateFilm(filmToUpdate, stm);
				}

			} catch (InterruptedException e) {
				// e.printStackTrace();
				Session.pool.killAll(lg.getLoaderTask());
				return null;
			}
			Session.pool.killAll(lg.getLoaderTask());
			UIUpdater.setWidgetEnable(cancel, true);
			if (isProgram) {
				UIUpdater.setWidgetEnable(((Button) vals[4]), true);
				UIUpdater.setWidgetEnable(((Button) vals[5]), true);
				UIUpdater.setWidgetEnable(((Button) vals[6]), true);
				UIUpdater.changeScreen((Composite) vals[7]);
			} else {
				UIUpdater.setWidgetEnable(((Button) vals[4]), true);
				UIUpdater.setWidgetEnable(((Button) vals[5]), true);
				UIUpdater.setWidgetEnable(((Text) vals[6]), true);
				UIUpdater.setWidgetEnable(((Text) vals[7]), true);
				UIUpdater.setWidgetEnable(((Button) vals[8]), true);
				UIUpdater.changeScreen((Composite) vals[9]);
			}

			lg.hideLoader();
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class SearchPersonTask extends AsyncTask<Object> {

		public SearchPersonTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {

			String query = (String) vals[0];
			Table table = (Table) vals[1];
			String typeOfPerson = (String) vals[2];
			LoaderGif lg = (LoaderGif) vals[3];
			Button add = (Button) vals[4];
			boolean isProgram = (Boolean) vals[5];
			boolean isActor = false;
			List<PersonRes> personRes = null;
			try {
				Statement stm = Session.connectionPool.getStatement(this);
				if (typeOfPerson.equals("actor")) {
					personRes = Session.DB.getMediaManagment()
							.getAllActorsStartWith(query, stm, !isProgram);
					isActor = true;
				} else if (typeOfPerson.equals("creator"))
					personRes = Session.DB.getMediaManagment()
							.getAllCreatorStartWith(query, stm);
				else if (typeOfPerson.equals("director"))
					personRes = Session.DB.getMediaManagment()
							.getAllDirectorStartWith(query, stm);

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				Session.pool.killAll(lg.getLoaderTask());
				return null;
			}
			Session.pool.killAll(lg.getLoaderTask());
			UIUpdater.updatePersonTable(personRes, table, add, isProgram,
					isActor);
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.pool.killAll(((LoaderGif) vals[3]).getLoaderTask());
			Session.connectionPool.stopDBoperation(this);
		}
	}

	public static class SearchMediaTask extends AsyncTask<Object> {

		public SearchMediaTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {

			String query = (String) vals[0];
			Table table = (Table) vals[1];
			LoaderGif lg = (LoaderGif) vals[2];
			Button add = (Button) vals[3];
			List<MediaRes> mediaRes = null;

			try {
				Statement stm = Session.connectionPool.getStatement(this);
				mediaRes = Session.DB.getMediaManagment().getAllFilmStartWith(
						query, stm);
			} catch (InterruptedException e) {
				Session.pool.killAll(lg.getLoaderTask());
				return null;
			}

			Session.pool.killAll(lg.getLoaderTask());
			UIUpdater.updateMediaTable(mediaRes, table, add);
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}
	}

	public static class SearchTask extends AsyncTask<Object> {

		public SearchTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {

			// the order is: film, program, actor, creator, director
			boolean[] whatToSearch = (boolean[]) vals[0];
			String query = (String) vals[1];
			LoaderGif lg = (LoaderGif) vals[2];
			List<MediaRes> filmRes = null;
			List<MediaRes> programRes = null;
			List<PersonRes> actorRes = null;
			List<PersonRes> creatorRes = null;
			List<PersonRes> directorRes = null;

			if (whatToSearch[0])
				Session.poolForSearch.addTaskToPool(true, new searchSpesTask(
						display, 0, query));
			// filmRes = Session.DB.getAllFilmStartWith(query);
			if (whatToSearch[1])
				Session.poolForSearch.addTaskToPool(true, new searchSpesTask(
						display, 1, query));
			// programRes = Session.DB.getAllProgramStartWith(query);
			if (whatToSearch[2])
				Session.poolForSearch.addTaskToPool(true, new searchSpesTask(
						display, 2, query));
			// actorRes = Session.DB.getAllActorsStartWith(query);
			if (whatToSearch[3])
				Session.poolForSearch.addTaskToPool(true, new searchSpesTask(
						display, 3, query));
			// creatorRes = Session.DB.getAllCreatorStartWith(query);
			if (whatToSearch[4])
				Session.poolForSearch.addTaskToPool(true, new searchSpesTask(
						display, 4, query));
			// directorRes = Session.DB.getAllDirectorStartWith(query);

			List<Object> lst = Session.poolForSearch.getResults();
			Session.poolForSearch.cleanResults();

			if (lst != null) {
				for (Object o : lst) {
					if (o instanceof MediaRet) {
						if (((MediaRet) o).getId() == 0)
							filmRes = ((MediaRet) o).getMedias();
						else
							programRes = ((MediaRet) o).getMedias();
					} else {
						if (((PersonsRet) o).getId() == 2)
							actorRes = ((PersonsRet) o).getPersons();
						else if (((PersonsRet) o).getId() == 3)
							creatorRes = ((PersonsRet) o).getPersons();
						else
							directorRes = ((PersonsRet) o).getPersons();
					}

				}

				SearchResult searchRes = new SearchResult(filmRes, programRes,
						actorRes, creatorRes, directorRes);
				UIUpdater.updateSearchTBL(searchRes);
			}
			/*
			 * try { Thread.sleep(1000); } catch (InterruptedException e) { //
			 * TODO Auto-generated catch block
			 * Session.pool.killAll(lg.getLoaderTask()); return null; }
			 */
			Session.pool.killAll(lg.getLoaderTask());

			return null;
		}

		@Override
		public void onInterrupt() {
			LoaderGif lg = (LoaderGif) vals[2];
			System.out.println("sdsdsdsd");
			Session.poolForSearch.killAll();
			// Session.pool.killAll(lg.getLoaderTask());

		}

	}

	private static class searchSpesTask extends AsyncTask<Object> {

		public searchSpesTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {
			int taskNum = (Integer) vals[0];
			String query = (String) vals[1];
			try {

				PersonsRet personRet = null;
				MediaRet mediaRet = null;
				Statement stm = Session.connectionPool.getStatement(this);
				switch (taskNum) {
				case 0:
					mediaRet = new MediaRet(Session.DB.getMediaManagment()
							.getAllFilmStartWith(query, stm), 0);
					Session.connectionPool.stopDBoperation(this);
					return mediaRet;
				case 1:
					mediaRet = new MediaRet(Session.DB.getMediaManagment()
							.getAllProgramStartWith(query, stm), 1);
					Session.connectionPool.stopDBoperation(this);
					return mediaRet;
				case 2:
					personRet = new PersonsRet(Session.DB.getMediaManagment()
							.getAllActorsStartWith(query, stm), 2);
					Session.connectionPool.stopDBoperation(this);
					return personRet;
				case 3:
					personRet = new PersonsRet(Session.DB.getMediaManagment()
							.getAllCreatorStartWith(query, stm), 3);
					Session.connectionPool.stopDBoperation(this);
					return personRet;
				case 4:
					personRet = new PersonsRet(Session.DB.getMediaManagment()
							.getAllDirectorStartWith(query, stm), 4);
					Session.connectionPool.stopDBoperation(this);
					return personRet;
				}
			} catch (InterruptedException e) {
				return null;
			}
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			System.out.println("here");
			Session.connectionPool.stopDBoperation(this);

		}
	}

	private static class PersonsRet {
		private List<PersonRes> persons;
		private int id = 0;

		public PersonsRet(List<PersonRes> persons, int id) {
			super();
			this.persons = persons;
			this.id = id;
		}

		public synchronized int getId() {
			return id;
		}

		public synchronized List<PersonRes> getPersons() {
			return persons;
		}
	}

	private static class MediaRet {
		private List<MediaRes> medias;
		private int id = 0;

		public MediaRet(List<MediaRes> medias, int id) {
			super();
			this.medias = medias;
			this.id = id;
		}

		public synchronized int getId() {
			return id;
		}

		public synchronized List<MediaRes> getMedias() {
			return medias;
		}
	}

	public static class AddPersonTask extends AsyncTask<Object> {

		public AddPersonTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {

			String personType = (String) vals[0];
			String fName = (String) vals[1];
			String lName = (String) vals[2];
			LoaderGif lg = (LoaderGif) vals[3];
			try {
				Statement stm = Session.connectionPool.getStatement(this);
				if (personType.equals("actor"))
					Session.DB.getMediaManagment().newActor(fName, lName, stm);
				else if (personType.equals("creator"))
					Session.DB.getMediaManagment()
							.newCreator(fName, lName, stm);
				else
					Session.DB.getMediaManagment().newDirector(fName, lName,
							stm);

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				Session.pool.killAll(lg.getLoaderTask());
				return null;
			}

			UIUpdater.clearAddPersonWindow();
			Session.pool.killAll(lg.getLoaderTask());
			lg.hideLoader();
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class GetMediaTask extends AsyncTask<Object> {

		public GetMediaTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {

			int mediaID = (Integer) vals[0];
			String mediaType = (String) vals[1];
			Composite editMedia = (Composite) vals[2];
			try {
				Statement stm = Session.connectionPool.getStatement(this);

				if (mediaType.equals("program")) {

					Session.gui.getEditProgram().setProgram(
							Session.DB.getMediaManagment().getProgramFromDB(
									mediaID, stm));

					UIUpdater.prepareMediaPage(editMedia, true);
				} else if (mediaType.equals("film")) {
					Session.gui.getEditFilm().setFilm(
							Session.DB.getMediaManagment().getFilmFromDB(
									mediaID, stm));
					UIUpdater.prepareMediaPage(editMedia, false);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class LoaderTask extends AsyncTask<Object> {

		public LoaderTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {
			int imageNum = 0;
			ImageLoader loader = (ImageLoader) vals[0];
			Canvas canvas = (Canvas) vals[1];
			GC gc = (GC) vals[2];

			try {
				while (true) {
					Thread.sleep(loader.data[imageNum].delayTime * 10);
					imageNum++;
					imageNum = imageNum % loader.data.length;
					UIUpdater.updateLoader(imageNum, canvas, gc, loader);

				}

			} catch (Exception e) {
				UIUpdater.setWidgetVisibile(canvas, false);
			}

			return null;
		}

		@Override
		public void onInterrupt() {
			UIUpdater.setWidgetVisibile(((Canvas) vals[1]), false);
		}

	}

	public static class UpdateUserScoreTask extends AsyncTask<Object> {

		public UpdateUserScoreTask(Display display, Object... vals) {
			super(display, vals);
		}

		@SuppressWarnings("unused")
		@Override
		public Object doInBackground() throws TaskRunError {
			LoaderGif lg = (LoaderGif) vals[0];
			int userID = (Integer) vals[1];
			String mod = (String) vals[2];
			int score = (Integer) vals[3];
			Button continueStats = (Button) vals[4];
			Label updateDB = (Label) vals[5];
			try {
				Statement stm = Session.connectionPool.getStatement(this);
				Session.DB.getUserManagment().updateUserScore(userID, score,
						mod, stm);

			} catch (InterruptedException e) {
				// e.printStackTrace();
				Session.poolTheQuestions.killAll(lg.getLoaderTask());
				return null;
			}
			Session.poolTheQuestions.killAll(lg.getLoaderTask());
			UIUpdater.setWidgetVisibile(continueStats, true);
			UIUpdater.setWidgetVisibile(updateDB, false);
			lg.hideLoader();

			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class UpdateUsersTask extends AsyncTask<Object> {

		public UpdateUsersTask(Display display, Object... vals) {
			super(display, vals);

		}

		@SuppressWarnings("unchecked")
		@Override
		public Object doInBackground() throws TaskRunError {

			List<Integer> usersToDelete = (List<Integer>) vals[0];
			List<Integer> usersToMakeAdmin = (List<Integer>) vals[1];
			List<Integer> usersToMakePlayer = (List<Integer>) vals[2];
			List<User> users = (List<User>) vals[3];
			LoaderGif lg = (LoaderGif) vals[4];

			try {
				Statement stm = Session.connectionPool.getStatement(this);
				Session.DB.getUserManagment().changeUsersPriv(usersToMakeAdmin,
						usersToMakePlayer, stm);
				// Session.DB.deleteUsers(usersToDelete);
			} catch (InterruptedException e) {
				Session.pool.killAll(lg.getLoaderTask());
				return null;
			}

			List<User> newUsers = new ArrayList<User>();

			for (User u : users) {
				if (!usersToDelete.contains(u.getId())) {
					newUsers.add(u);
				}
			}

			Session.pool.killAll(lg.getLoaderTask());
			UIUpdater.updateUsersTable(newUsers);
			Session.connectionPool.stopDBoperation(this);

			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class GetUsersTask extends AsyncTask<Object> {

		public GetUsersTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {

			LoaderGif lg = (LoaderGif) vals[0];
			List<User> users = null;
			try {
				Statement stm = Session.connectionPool.getStatement(this);
				users = Session.DB.getUserManagment().getAllUsers(stm);
			} catch (InterruptedException e) {
				Session.pool.killAll(lg.getLoaderTask());
				return null;
			}

			Session.pool.killAll(lg.getLoaderTask());
			UIUpdater.updateUsersTable(users);
			// UIUpdater.setWidgetVisibile(loadingLBL, false);
			Session.connectionPool.stopDBoperation(this);
			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class GetDB_StatsTask extends AsyncTask<Object> {

		public GetDB_StatsTask(Display display, Object... vals) {
			super(display, vals);
		}

		@SuppressWarnings("unused")
		@Override
		public Object doInBackground() throws TaskRunError {
			LoaderGif lg = (LoaderGif) vals[0];
			String str = "";
			try {
				Statement stm = Session.connectionPool.getStatement(this);
				str = Session.DB.getDb_stats().getDBstats(stm);
			} catch (InterruptedException e) {
				// e.printStackTrace();
				Session.pool.killAll(lg.getLoaderTask());
				return null;
			}
			Session.pool.killAll(lg.getLoaderTask());
			UIUpdater.editDB(str);

			lg.hideLoader();

			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class OpenConnectionsTask extends AsyncTask<Object> {

		public OpenConnectionsTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {

			LoaderGif lg = (LoaderGif) vals[0];

			Session.connectionPool = new ConnectionPool();

			// if (SharedPref.firstRun) {

			Statement stm;
			try {
				stm = Session.connectionPool.getStatement(this);
				Session.DB.getUserManagment().createAdmin(stm);
			} catch (InterruptedException e) {
				e.printStackTrace();
				Session.pool.killAll(lg.getLoaderTask());
				return null;
			}
			Session.connectionPool.stopDBoperation(this);
			// }

			Session.pool.killAll(lg.getLoaderTask());
			UIUpdater.afterConnecting();

			return null;
		}

		@Override
		public void onInterrupt() {
			if (SharedPref.firstRun)
				Session.connectionPool.stopDBoperation(this);

		}

	}

	public static class LongDBoperationTask extends AsyncTask<Object> {

		public LongDBoperationTask(Display display, Object... vals) {
			super(display, vals);
		}

		@Override
		public Object doInBackground() throws TaskRunError {

			LoaderGif lg = (LoaderGif) vals[0];
			int operationType = (Integer) vals[1];
			try {

				Connection conn = Session.connectionPool.getConnection(this);

				if (operationType == 1) {
					Session.DB.getManageDB().removeDataBase(conn);
				} else if (operationType == 2) {
					//Session.DB.getManageDB().updateDataBase(conn);
					Session.DB.getManageDB().removeDataBase(conn);
					Session.DB.getManageDB().createDataBase(conn);
				} else {
					Session.DB.getManageDB().createDataBase(conn);
				}

			} catch (InterruptedException e) {
				e.printStackTrace();
				Session.pool.killAll(lg.getLoaderTask());
				return null;
			}
			Session.connectionPool.returnConnection(this);
			Session.pool.killAll(lg.getLoaderTask());
			UIUpdater.afterDBmanage();

			return null;
		}

		@Override
		public void onInterrupt() {
			Session.connectionPool.returnConnection(this);
		}

	}

}
